package boogui.movie;

import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import boogui.db.BooguiDAO;
import boogui.db.IBooguiDAO;
import boogui.db.MovieSQL;

public class MovieDAO implements IMovieDAO {	
	IBooguiDAO bdao = null;
	MovieSQL sql = null;

	public MovieDAO() {		
		bdao = new BooguiDAO();
		sql = new MovieSQL();
	}

	@Override
	public List<MovieVO> selectMovie(MovieVO mv) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<MovieVO> result = new ArrayList<>();

		try {
			conn = bdao.openDatabase();
			pstmt = conn.prepareStatement(sql.getSelectMovieSQL());
			pstmt.setString(1, mv.getMovtitle());
			rs = pstmt.executeQuery();
			
			while (rs.next()) {
				mv.setMovno(rs.getString("movno"));
				mv.setMovtitle(rs.getString("title"));
				mv.setMovgenre1(rs.getString("genre1"));
				mv.setMovgenre2(rs.getString("genre2"));
				mv.setMovdirector(rs.getString("director"));
				mv.setMovactor1(rs.getString("actor1"));
				mv.setMovactor2(rs.getString("actor2"));
				mv.setMovactor3(rs.getString("actor3"));
				mv.setMovrating(rs.getString("rating"));
				mv.setMovsynop(rs.getString("synop"));
				mv.setMovruntime(rs.getString("runningtime"));
				mv.setMovplaydate(rs.getString("playdate"));
				mv.setMovisplay(rs.getString("isplay"));
				mv.setMovresv(rs.getString("reserverate"));
				result.add(mv);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			bdao.closeDatabase(conn, pstmt, rs);
		}

		return result;
	}		

	@Override
	public BufferedImage readImage(String str) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		BufferedImage image = null;
		Blob lob = null;
		try {
			conn = bdao.openDatabase();
			pstmt = conn.prepareStatement(sql.getSelectPosterSQL());
			pstmt.setString(1, str);	
			rs = pstmt.executeQuery();
					
			while (rs.next()) {
				lob = rs.getBlob("poster");
			}
			InputStream in = lob.getBinaryStream();
			image = ImageIO.read(in);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			bdao.closeDatabase(conn, pstmt, null);
		}
		return image;
	}

}